package com.sxm.yiwei.activitis;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sxm.yiwei.MainActivity;
import com.sxm.yiwei.R;
import com.sxm.yiwei.adapters.FWContentImgAdapter;
import com.sxm.yiwei.adapters.SearchGridAdapter;
import com.sxm.yiwei.beans.ServiceContent;
import com.sxm.yiwei.tools.BookPayActivity;
import com.sxm.yiwei.tools.ErrType;
import com.sxm.yiwei.tools.ImgSwitcherActivity;
import com.sxm.yiwei.tools.IsLogin;
import com.sxm.yiwei.utils.InternetAddressUtis;
import com.sxm.yiwei.views.MyGridView;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

public class FwContentTwoActivity extends BaseActivity implements View.OnClickListener {

    private SharedPreferences sharedPreferences;
    private String token;
    private String userId;
    private String appId;
    private String serviceId;
    private ScrollView contentscroll;
    private String amount;
    private String toid;
    private String shopId;
    private Integer splitindex;
    private ImageView fwback;
    private RelativeLayout allbt;
    private MyGridView fwgridview;
    private TextView buyservicebt;
    private TextView fwaword;
    private LinearLayout collectbt;
    private LinearLayout toShopbt;
    private LinearLayout addcarbt;
    private Button add;
    private Button reduce;
    private TextView result;
    private CheckBox box1;
    private CheckBox box2;
    private CheckBox box3;
    private CheckBox box4;
    private CheckBox box5;
    private TextView serviceName;
    private ImageView showImg1;
    private ImageView showImg2;
    private ImageView showImg3;
    private TextView turnovernumber;
    private TextView serviceprice;
    private TextView commentnumber;
    private TextView rewordnumber;
    private TextView serviceexplain;
    private ImageView explainimg;
    private ImageView care;
    private LinearLayout weiyixia;
    private EditText awordmoney;
    private AlertDialog dialog;
    private String money;
    private JSONArray showImages;
    private JSONArray introImages;
    private String isCollection;
    private AlertDialog dialog10;
    private ImageView backmain;
    private MyGridView gridimgs;
    private String TAG ="FW";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fwcontent);
        sharedPreferences = getSharedPreferences("userlogin", Context.MODE_PRIVATE);
        token = sharedPreferences.getString("token", "");
        userId = sharedPreferences.getString("userId", "");
        appId = sharedPreferences.getString("appid", "");
        Intent intent = getIntent();
        serviceId = intent.getStringExtra("id");

        contentscroll = (ScrollView) findViewById(R.id.fw_content_scroll);
        contentscroll.smoothScrollTo(0,0);

        initFwContentView();
        getServiceData(intent.getStringExtra("id"));
    }

    // 获取服务详情
    private void getServiceData(String id) {
        RequestParams params = new RequestParams(InternetAddressUtis.Url+InternetAddressUtis.GETSERVICEDATA);
        params.addHeader("Content-Type","application/json");
        if (appId.equals("")){
            params.addHeader("appId","337cb33f-83bd-11e7-9812-00163e0a3457");
        }else {
            params.addHeader("appId",appId);
        }
        params.addHeader("userId",userId);
        JSONObject object = new JSONObject();
        object.put("serviceId",id);
        params.addParameter("params",object.toJSONString());
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {

                getData(result);

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

                ErrType.errType(FwContentTwoActivity.this,ex);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private void getData(String result) {

        JSONObject obj = JSON.parseObject(result);
        String data = obj.getString("data");
        JSONObject obj1 = JSON.parseObject(data);
        amount = obj1.getString("amount");
        toid = obj1.getString("id");
        String intro = obj1.getString("intro");
        String isCart = obj1.getString("isCart");
        String name = obj1.getString("name");
        String unit = obj1.getString("unit");
        String volume = obj1.getString("volume");
        isCollection = obj1.getString("isCollection");
        if (isCollection!=null){
            if (isCollection.equals("true")){
                care.setImageResource(R.mipmap.guanzhulanse);
            }else {
                care.setImageResource(R.mipmap.guanzhuhuise);
            }
        }else {}

        String promise = obj1.getString("promise");
        shopId = obj1.getString("shopId");
        String rewardCount = obj1.getString("rewardCount");
        String commentCount = obj1.getString("commentCount");
        if (!promise.equals("")&!promise.equals(null)){

            String[] split = promise.split(",");
            for (int i = 0; i < split.length; i++) {
                splitindex = Integer.valueOf(split[i]);

                switch (splitindex){
                    case 1:
                        box1.setChecked(true);
                        break;
                    case 2:
                        box2.setChecked(true);
                        break;
                    case 3:
                        box3.setChecked(true);
                        break;
                    case 4:
                        box4.setChecked(true);
                        break;
                    case 5:
                        box5.setChecked(true);
                        break;
                }
            }

        }else {}
        introImages = obj1.getJSONArray("introImages");
        JSONArray otherService = obj1.getJSONArray("otherService");
        showImages = obj1.getJSONArray("showImages");

        serviceName.setText(name);
        serviceexplain.setText(intro);
        if (unit.equals("1")){
            serviceprice.setText(amount +" 元/时");
        }else if (unit.equals("2")){
            serviceprice.setText(amount +" 元/天");
        }else if (unit.equals("3")){
            serviceprice.setText(amount +" 元/月");
        }else {
            serviceprice.setText(amount+" 元/单");
        }

        turnovernumber.setText(volume);
        if (commentCount!=null){
            commentnumber.setText(commentCount);
        }else {
            commentnumber.setText("0");
        }
        if (rewardCount!=null){
            rewordnumber.setText(rewardCount+" 人打赏");
        }else {
            rewordnumber.setText("0"+" 人打赏");
        }
        if (showImages.size()!=0){
            FWContentImgAdapter imgAdapter = new FWContentImgAdapter(FwContentTwoActivity.this,showImages);
            gridimgs.setAdapter(imgAdapter);
            int itemWidth = (int)(125 * this.getResources().getDisplayMetrics().density);
            int itemSize = showImages.size();
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(itemSize * itemWidth, LinearLayout.LayoutParams.WRAP_CONTENT);
            gridimgs.setLayoutParams(params);
            gridimgs.setNumColumns(itemSize);
            gridimgs.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Intent in = new Intent(FwContentTwoActivity.this, ImgSwitcherActivity.class);
                    in.putExtra("position",position);
                    in.putExtra("imgs",showImages);
                    startActivity(in);
                }
            });
        }else {}
        if (introImages.size()!=0){
            x.image().bind(explainimg,InternetAddressUtis.IMG_URL+ introImages.get(0));
        }else {
            explainimg.setVisibility(View.GONE);
        }
        List<ServiceContent.DataBean.OtherServiceBean> gridlist = new ArrayList<>();
        if (otherService.size()!=0){
            for (int i = 0; i < otherService.size(); i++) {
                JSONObject obj2 = JSON.parseObject(String.valueOf(otherService.get(i)));
                String amount1 = obj2.getString("amount");
                String id1 = obj2.getString("id");
                String name1 = obj2.getString("name");
                String serviceAvatar = obj2.getString("serviceAvatar");
                String unit1 = obj2.getString("unit");
                ServiceContent.DataBean.OtherServiceBean serviceBean = new ServiceContent.DataBean.OtherServiceBean();
                serviceBean.setAmount(Integer.valueOf(amount1));
                serviceBean.setServiceAvatar(serviceAvatar);
                serviceBean.setName(name1);
                serviceBean.setId(id1);
                serviceBean.setUnit(Integer.valueOf(unit1));
                gridlist.add(serviceBean);

            }

        }else {}
        final SearchGridAdapter adapter = new SearchGridAdapter(FwContentTwoActivity.this,gridlist);
        fwgridview.setAdapter(adapter);
        adapter.notifyDataSetChanged();
        adapter.setOnGridItem(new SearchGridAdapter.OnClickgridItemInf() {
            @Override
            public void OnClickGridItem(int p) {
                ServiceContent.DataBean.OtherServiceBean serviceBean = adapter.gridlist.get(p);
                String id1 = serviceBean.getId();
                Intent intent = new Intent(FwContentTwoActivity.this,FwContentTwoActivity.class);
                intent.putExtra("id",id1);
                startActivity(intent);
               // finish();
            }
        });

    }

    private void initFwContentView() {
        gridimgs = (MyGridView) findViewById(R.id.fw_content_gridimgs);

        fwback = (ImageView) findViewById(R.id.fw_contentback);
        allbt = (RelativeLayout) findViewById(R.id.fw_contentallbt);
        fwgridview = (MyGridView) findViewById(R.id.fw_content_gridview);
        buyservicebt = (TextView) findViewById(R.id.fw_content_buyservicebt);
        fwaword = (TextView) findViewById(R.id.fw_content_aword);
        collectbt = (LinearLayout) findViewById(R.id.fw_content_collectservice);
        toShopbt = (LinearLayout) findViewById(R.id.fw_content_toshop);
        addcarbt = (LinearLayout) findViewById(R.id.fw_content_addcar);
        add = (Button) findViewById(R.id.add);
        reduce = (Button) findViewById(R.id.reduce);
        result = (TextView) findViewById(R.id.t_result);
        box1 = (CheckBox) findViewById(R.id.fw_content_box1);
        box2 = (CheckBox) findViewById(R.id.fw_content_box2);
        box3 = (CheckBox) findViewById(R.id.fw_content_box3);


        box4 = (CheckBox) findViewById(R.id.fw_content_box4);
        box5 = (CheckBox) findViewById(R.id.fw_content_box5);
        backmain = (ImageView) findViewById(R.id.fw_content_backmain);
        serviceName = (TextView) findViewById(R.id.fw_content_servicename);
        turnovernumber = (TextView) findViewById(R.id.fw_content_turnovernumber);
        serviceprice = (TextView) findViewById(R.id.fw_content_pricetext);
        commentnumber = (TextView) findViewById(R.id.fw_content_commentnumber);
        rewordnumber = (TextView) findViewById(R.id.fw_content_reaordnumber);
        serviceexplain = (TextView) findViewById(R.id.fw_content_serviceexplain);
        explainimg = (ImageView) findViewById(R.id.fw_content_servicexplainimg);
        care = (ImageView) findViewById(R.id.fw_content_care);
        weiyixia = (LinearLayout) findViewById(R.id.fwcontent_weiyixia);


        // 点击事件监听
        backmain.setOnClickListener(this);

        explainimg.setOnClickListener(this);
        add.setOnClickListener(this);
        reduce.setOnClickListener(this);
        result.setOnClickListener(this);
        fwback.setOnClickListener(this);
        allbt.setOnClickListener(this);
        buyservicebt.setOnClickListener(this);
        fwaword.setOnClickListener(this);
        collectbt.setOnClickListener(this);
        toShopbt.setOnClickListener(this);
        addcarbt.setOnClickListener(this);
        weiyixia.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.fw_content_backmain:
                Intent intent = new Intent(FwContentTwoActivity.this, MainActivity.class);
                startActivity(intent);
                AppManager.getAppManager().finishAllActivity();
                break;
            case R.id.fw_content_servicexplainimg:
                if (introImages.size()!=0){
                    Intent in = new Intent(FwContentTwoActivity.this, ImgSwitcherActivity.class);
                    in.putExtra("position",0);
                    in.putExtra("imgs",introImages);
                    startActivity(in);

                }else {

                }
                break;
            case R.id.fwcontent_weiyixia:
                Toast.makeText(this, "功能开发中，敬请期待", Toast.LENGTH_SHORT).show();
                break;
            case R.id.fw_contentallbt:
               if (!token.equals("")){
                   Intent into = new Intent(FwContentTwoActivity.this,FWAllDiscussActivity.class);
                   into.putExtra("id", toid);
                   startActivity(into);
               }else {
                   IsLogin.isLogin();
               }
                break;
            case R.id.add:
                int aNumber = Integer.parseInt(String.valueOf(result.getText()));
                aNumber++;
                result.setText(String.valueOf(aNumber));
                break;
            case R.id.reduce:
                int rNumber = Integer.parseInt(String.valueOf(result.getText()));
                if (rNumber>0){
                    rNumber--;
                    result.setText(String.valueOf(rNumber));
                }else{
                    Toast.makeText(this, "对不起,奴家不接受调戏", Toast.LENGTH_SHORT).show();
                }

                break;
            case R.id.fw_content_collectservice:// 关注服务

               if (!token.equals("")){
                   AlertDialog.Builder builder10 = new AlertDialog.Builder(FwContentTwoActivity.this);
                   View view10 = LayoutInflater.from(FwContentTwoActivity.this).inflate(R.layout.cancel_servicedialog, null);
                   builder10.setView(view10);
                   Button cancelbt = (Button) view10.findViewById(R.id.cancel_cancelbt);
                   Button surebt = (Button) view10.findViewById(R.id.cancel_surebt);
                   TextView t2 = (TextView) view10.findViewById(R.id.cancel_t2);
                   cancelbt.setText("否");
                   surebt.setText("是");
                   if (isCollection.equals("true")){
                       t2.setText("是否取消关注");
                   }else {
                       t2.setText("是否关注");
                   }

                   dialog10 = builder10.create();
                   cancelbt.setOnClickListener(new View.OnClickListener() {
                       @Override
                       public void onClick(View v) {
                           dialog10.dismiss();
                       }
                   });
                   surebt.setOnClickListener(new View.OnClickListener() {
                       @Override
                       public void onClick(View v) {
                           collectService();
                           dialog10.dismiss();
                       }
                   });
                   dialog10.show();
               }else {
                   IsLogin.isLogin();
               }
                break;
            case R.id.fw_content_toshop://收藏店铺
                Intent i = new Intent(FwContentTwoActivity.this,FWShopActivity.class);
                i.putExtra("id", shopId);
                startActivity(i);
                break;
            case R.id.fw_content_addcar:
                if (!token.equals("")){
                    addCar();
                }else {
                    IsLogin.isLogin();
                }

                break;
            case R.id.fw_contentback:
                finish();
                break;
            case R.id.fw_content_buyservicebt:
               if (!token.equals("")){
                   Intent in = new Intent(FwContentTwoActivity.this,FwBuyServiceActivity.class);
                   in.putExtra("id", toid);
                   in.putExtra("price", amount);
                   startActivity(in);
               }else {
                   IsLogin.isLogin();
               }
                break;
            case R.id.fw_content_aword:

               if (!token.equals("")){
                   AlertDialog.Builder builder5 = new AlertDialog.Builder(this,R.style.NoBackGroundDialog);
                   View view = LayoutInflater.from(this).inflate(R.layout.fw_dialogall, null);
                   View awordbt = view.findViewById(R.id.fw_awordbt);
                   awordmoney = (EditText) view.findViewById(R.id.fw_awordmoney);
                   final View othermoney = view.findViewById(R.id.fw_othermoney);
                   awordbt.setOnClickListener(new View.OnClickListener() {
                       @Override
                       public void onClick(View v) {
                           String text = String.valueOf(awordmoney.getText());
                           rewardService();
                       }
                   });
                   othermoney.setOnClickListener(new View.OnClickListener() {
                       @Override
                       public void onClick(View v) {
                           awordmoney.setText("");
                           awordmoney.requestFocus();
                           awordmoney.setBackgroundColor(getResources().getColor(R.color.colorAb));
                           othermoney.setVisibility(View.GONE);

                       }
                   });
                   builder5.setView(view);
                   dialog = builder5.create();
                   dialog.show();
               }else {
                   IsLogin.isLogin();
               }
                break;
        }
    }
    // 加入购物车
    private void addCar() {
        RequestParams params = new RequestParams(InternetAddressUtis.Url+InternetAddressUtis.ADDCARSERVICE);
        params.addHeader("Content-Type","application/json");
        params.addHeader("token",token);
        params.addHeader("appId",appId);
        params.addHeader("userId",userId);
        JSONObject object = new JSONObject();
        object.put("serviceId",serviceId);
        params.setBodyContent(object.toJSONString());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Toast.makeText(FwContentTwoActivity.this, "已经加入购物车", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ErrType.errType(FwContentTwoActivity.this,ex);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    //收藏服务
    private void collectService() {
        RequestParams params = new RequestParams(InternetAddressUtis.Url+InternetAddressUtis.COLLECTSERVICE);
        params.addHeader("Content-Type","application/json");
        params.addHeader("token",token);
        params.addHeader("appId",appId);
        params.addHeader("userId",userId);

        JSONObject object = new JSONObject();
        object.put("serviceId",serviceId);
        params.setBodyContent(object.toJSONString());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if (isCollection.equals("true")){
                    care.setImageResource(R.mipmap.guanzhuhuise);
                    isCollection = "false";
                    Toast.makeText(FwContentTwoActivity.this, "已取消收藏", Toast.LENGTH_SHORT).show();

                }else {
                    isCollection = "true";
                    care.setImageResource(R.mipmap.guanzhulanse);
                    Toast.makeText(FwContentTwoActivity.this, "服务收藏成功", Toast.LENGTH_SHORT).show();

                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ErrType.errType(FwContentTwoActivity.this,ex);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    // 打赏服务
    private void rewardService() {
        money = String.valueOf(awordmoney.getText());
        RequestParams params = new RequestParams(InternetAddressUtis.Url+InternetAddressUtis.REWARDSERVICE);
        params.addHeader("Content-Type","application/json");
        params.addHeader("token",token);
        params.addHeader("appId",appId);
        params.addHeader("userId",userId);

        JSONObject object = new JSONObject();
        object.put("serviceId",serviceId);
        object.put("amount", money);

        params.setBodyContent(object.toJSONString());

        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {

                JSONObject obj = JSON.parseObject(result);
                String data = obj.getString("data");
                JSONObject obj1 = JSON.parseObject(data);
                String rewardId = obj1.getString("rewardId");
                // 支付打赏
                Intent intent = new Intent(FwContentTwoActivity.this,BookPayActivity.class);
                intent.putExtra("id",rewardId);
                intent.putExtra("amount", money);
                intent.putExtra("from","reward");
                intent.putExtra("alipay",InternetAddressUtis.ALIPAYREWARDSERVICE);
                intent.putExtra("yivipay",InternetAddressUtis.YIVIPAYREWARDSERVICE);
                startActivity(intent);
                dialog.dismiss();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ErrType.errType(FwContentTwoActivity.this,ex);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

}
